/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  ToolbarAndroid,
  Dimensions,
  BackHandler,
  Platform,
  ListView,
} from 'react-native';

import Common from '../../component/common';
import ScreenUtils from '../../component/ScreenUtils';
import ToolbarComponent from '../../component/ToolbarComponent';

import SubscriptionItem from '../me/part/subscriptionItem';
import InfoItem from '../me/part/infoItem';
import VarietyItem from '../me/part/varietyItem';

import Toast from 'react-native-root-toast';

import Loading from '../../component/loading';
import LoadError from '../../component/loadError';

const wechat=require('../../images/wechat.png');
const weibo=require('../../images/weibo.png');
const web=require('../../images/newspaper.png');

import Detail from '../home/detail';

export default class infoSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
    	dataSource: new ListView.DataSource({
        	rowHasChanged: (row1, row2) => row1 !== row2,
      	}),
      	keywords: this.props.did,
      	loading: true,
		success: false,
      	nowpage:1,
      	pagesize:12,
      	footer:0,
      	error:false,
      	noMoreData:false,
      	loadingmore:false,
      	title: ""
    };
    this.fetchData = this.fetchData.bind(this);
    this.totalList = [];
  }
  
  componentWillMount() {  
    if (Platform.OS === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }  
  }  
  componentWillUnmount() { 
  	this.timer && clearTimeout(this.timer);
    if (Platform.OS === 'android') {  
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }  
  } 
  componentDidMount(){
    this.fetchData();
  }
  determineCategory = (type) =>{
  	let category ={};
  	if(parseInt(type) == 1) {
  		category.title ="综艺";
  		category.searchUrl = '/search/programList';
  	}else if(parseInt(type) == 2){
  		category.title ="电影";
  		category.searchUrl = '/search/filmList';
  	}else if(parseInt(type) == 3){
  		category.title ="电视剧";
  		category.searchUrl = '/search/tvList';
  	}
  	return category;
  }
  fetchData(){
  	this.setState({
  	  	loadingMoreData:false,
  	  });
  	  let searchDada = this.determineCategory(this.props.parentId);
	  let formData = new FormData();
	  	formData.append("keywords",this.state.keywords);
	  	formData.append("nowpage",this.state.nowpage);
	  	formData.append("pagesize",this.state.pagesize);
	    Common.fetchData("post", searchDada.searchUrl , formData, (resp) => {
        var responseData = Common.page("listResult", resp);
        this.totalList = this.totalList.concat(responseData.result);
	    	this.setState({
  				dataSource:this.state.dataSource.cloneWithRows(this.totalList),
  				nowpage:responseData.np+1,
  				dataLength:responseData.total,
  				totalPage:responseData.ap,
          noMoreData:responseData.noMoreData,
  				loading: false,
  				success: true,
  				loadingFail:false,
  				loadingMoreData:true,
  			})
	    },() => {
	    	if(this.state.nowpage===1){
		      	this.setState({
					loading: false,
					success: false,
					errorMessage: "请求失败",
					loadingMoreData:true,
				})
		      }else{
		      	this.setState({
					loadingFail: true,
					loadingFailText:"加载失败，点我重新加载",
					loadingMoreData:true,
				})
		    }
	    },() => {
		    if(this.state.nowpage===1){
		      	this.setState({
					loading: false,
					success: false,
					errorMessage: "网络错误",
					loadingMoreData:true,
				})
		      }else{
		      	this.setState({
					loadingFail: true,
					loadingFailText:"加载失败，点我重新加载",
					loadingMoreData:true,
				})
		    }
	    });
  }
  
 _loadingMoreData(event){
  	if(!this.state.noMoreData && this.state.loadingMoreData){
  		this.fetchData();
  		
  	}
  }
  
  updown = (data) =>{
    var updown = {};
    // var data = data?parseInt(data):0;
    if(data > 0){
      updown.change = data;
      updown.icon = require('../../images/up.png');
    }else if(data < 0){
      updown.change = -data;
      updown.icon = require('../../images/down.png');
    }else{
      updown.change = "";
      updown.icon = require('../../images/still.png');
    }
    return updown;
  };
  refreshData(){
  	this.setState({
  		loadingFailText:"加载中...."
  	})
  	this.loadingAgain = setTimeout(() => {
  		this.fetchData();
  	},1000)
  }
  renderListHeader(){
  	return(
  		<Text style={styles.collectionCategory}>
			<Text>共{String(this.state.dataLength)}条</Text>
		</Text>
  	)
  }
  renderListFooter(){
  	return(
  		<View>
	  		{
				this.state.noMoreData ? <View style={styles.noMoreData}><Text style={styles.noMoreDataText}>数据已全部加载完毕</Text></View>:null
			}
			{
				this.state.loadingFail ? <TouchableOpacity onPress = {this.refreshData.bind(this)} style={styles.noMoreData}><Text style={styles.noMoreDataText}>{this.state.loadingFailText}</Text></TouchableOpacity>:null
			}
		</View>
  	)
  }
  renderVariety(data,sectionID,rowID) {
  	var updown = this.updown(data.rankingChanged);
  	var mydata = Common.keyWordHighlight(data.title);
    return (
      <TouchableOpacity style ={styles.vItemContainer} onPress={() => Common.onForward(this,Detail,data.type,data.id)}>
      	<View style={styles.vDescription}>
    			<View style={[styles.vDesImgWrap,{
    				marginLeft:ScreenUtils.scaleSize(20),
    			}]}>
    				{
    					data.pic3Path ? 
    						<Image 
    							style={styles.vDesImg} 
    							source={{uri: data.pic3Path }}
    						/>	: <View style={[styles.vDesImgWrap,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
    				}
    			</View>
    			<View style={styles.vDesInfo}>
    				<Text style={styles.vDesTitle} numberOfLines ={2}>
    					{
    				        mydata.map((item,i)=>{
    				          	if(item.hightLight){
    				          		return(
    				          			<Text key={i} style={{color:"red"}}>{item.data}</Text>
    				          		)
    				          	}else{
    				          		return(
    				          			<Text key={i}>{item.data}</Text>
    				          		)
    				          	}
    				        })
    			        }
    				</Text>
    				{
    					data.programTypeList ?
    						<View style={styles.vDesCategory}>
    							{
    								 data.programTypeList.map((item,i)=>{
    									return <View style={styles.vDes}><Text key={i} style={styles.vDesCategoryItem}>{item.title}</Text></View>
    								})
    							}
    						</View> : null
    				}
    				
    				<View style={styles.varietyContent}>
    					{
    						typeof(data.ranking)!=='undefined'?
    						<Text style={styles.vBillBoard}>榜单 <Text style={{color:"#ff5151",}}>No.{String(data.ranking)}</Text></Text> : null
    					}
    					{
    						typeof(data.rankingChanged)!=='undefined' ? <Image style={{marginLeft:5,}} source = {updown.icon}/> : null
    					}
    				</View>
    			</View>
      	</View>
      	<View style={styles.vIndex}>
      		<Text style={styles.vIndexTitle}>报道指数</Text>
      		<Text style={styles.vIndexNum}>{data.indexNumber ? String(parseFloat(data.indexNumber).toFixed(1)):"0.0"}</Text>
      	</View>
      </TouchableOpacity>
    );
  }
  
  render() {
  	let pageTitle = this.determineCategory(this.props.parentId).title;
    return (
      <View style ={styles.subscriptionContainer}>
  	    <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>搜索结果 - {pageTitle}</Text>
          </View>
        </ToolbarComponent>
		{
      		this.state.loading ?
				<Loading/>
					: (
						this.state.success ?
							<View style={{flex:1}}>
					      		<View style={styles.subscriptionItem}>
									<ListView
										dataSource={this.state.dataSource}
									    renderRow={this.renderVariety.bind(this)}
									    enableEmptySections={true}
									    showsVerticalScrollIndicator ={false}
									    onEndReached={this._loadingMoreData.bind(this)}
									    onEndReachedThreshold={500}
									    renderHeader = {this.renderListHeader.bind(this)}
									    renderFooter = {this.renderListFooter.bind(this)}
									    scrollRenderAheadDistance = {300}
									    removeClippedSubviews ={true}
									/>
						      	</View>
					      	</View>
						    : <LoadError reload={this.fetchData} reason={this.state.errorMessage}/>
					)      		
      }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  subscriptionContainer:{
    flex: 1,
  	backgroundColor:"#f6f6f6",
  	flexDirection:"column",
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: ScreenUtils.scaleSize(40),
  },
  vItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"row",
  	height:ScreenUtils.scaleSize(200),
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  	justifyContent:"center",
  	paddingLeft:ScreenUtils.scaleSize(30),
  	paddingRight:ScreenUtils.scaleSize(26),
  	marginBottom:ScreenUtils.scaleSize(14),
  },
  vDescription:{
  	flex:1,
  	height:ScreenUtils.scaleSize(200),
  	flexDirection:"row",
  	alignItems:"center",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingTop:ScreenUtils.scaleSize(14),
  	paddingBottom:ScreenUtils.scaleSize(14),
  },
  vDesImgWrap:{
  	width:ScreenUtils.scaleSize(110),
  	height:ScreenUtils.scaleSize(152),
  	justifyContent:"center",
  	alignItems:"center",
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  vDesImg:{
  	width:ScreenUtils.scaleSize(110),
  	height:ScreenUtils.scaleSize(152),
  },
  vDesInfo:{
  	flex:1,
  	height:ScreenUtils.scaleSize(152),
  	flexDirection:"column",
  	justifyContent:"space-around",
  	paddingLeft:ScreenUtils.scaleSize(26),
  },
  vDesTitle:{
  	fontSize:ScreenUtils.scaleSize(34),
  	color:"#000",
  },
  vDesCategory:{
  	flexDirection:"row",
  },
  vDes:{
    borderWidth:1,
    borderColor:"#ff4545",
    borderRadius:2,
    marginRight:5,
  },
  vDesCategoryItem:{
  	fontSize:ScreenUtils.scaleSize(18),
  	color:"#ff4545",
  	paddingLeft:5,
  	paddingRight:5,
  	
  	
  },
  vBillBoard:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#000",
  },
  vIndex:{
  	width:ScreenUtils.scaleSize(200),
  	alignItems:"flex-end",
  	justifyContent:"center",
  	paddingRight:ScreenUtils.scaleSize(20),
  },
  vIndexTitle:{
  	color:"#d7d7d7",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  varietyContent:{
  	flexDirection:"row",
  	alignItems:"center",
  },
  vIndexNum:{
  	fontSize:ScreenUtils.scaleSize(60),
  	color:"#ff4545",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  Item:{
  	marginTop:ScreenUtils.scaleSize(10),
  	borderTopWidth:1,
  	borderColor:"#ededed",
  },
  noMoreData:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(150),
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(14),
  },
  noMoreDataText:{
  	fontSize:ScreenUtils.scaleSize(18),
  }
});